/* Copyright 2014 Jan Wolter */
#include "stack.h"
#include "tableau.h"
#include "found.h"
#include "bouquet.h"
#include "waste.h"
#include "stock.h"
#include "solve.h"
#include "game.h"

char *gamename= "Ali Baba";
char *gameopt= "AUR";
Stack *gathered= NULL;
Stack *temp= NULL;

int aces= 0;
int unlimited= 0;
int dealrows= 0;

int nplayed= 0;
int nwon= 0;
int nabandoned= 0;
int cardsleft= 0;
int maxoff;
int baserank;

void setopt(char c)
{
    switch (c)
    {
	case 'A': aces++; break;
	case 'U': unlimited++; break;
	case 'R': dealrows++; break;
    }
}

/* This is the main program for setting up the current game */
void exec(int gather, int arif, int over, int cut)
{
    /* Could set things like ndeck, nsuit here */

    /* Build and shuffle the deck */
    Stack *shuf= mixcards(arif, over, cut);

    /* Create the foundations */
    superfound= sf_acebase;
    for (int s= 0; s < nsuit; s++)
	makeFound(1, s, +1, 13);

    if (aces)
    {
	for (int s= 0; s < nsuit; s++)
	{
	    Card *c= extractCard(shuf, 1, -1);
	    pushStack(stacks+foundation[nfound-nsuit+c->s].id, c);
	}
    }

    /* Create the tableau */
    for (int i= 0; i < 10; i++)
	makeTableau(dealrows ? 0 : 4, FLIP_NONE, shuf,
	    S_SAMESUIT, -1, S_SAMESUIT, -1, 1, F_ANYTHING, BREAK_NOWHERE, 0);
    if (dealrows)
	for (int r= 0; r < 4; r++)
	    for (int i= 0; i < 10; i++)
	    {
		Card *c= popStack(shuf);
		if (c) pushStack(stacks+tableau[i].id, c);
	    }


    if (unlimited)
    {
	makeBouquet(shuf,1,0);
    }
    else
    {
	/* Create the waste */
	makeWaste();

	/* Create the stock */
	makeStock(DT_WASTE, 1, 1, shuf);
    }

    freeStack(shuf);

    /* Print initial state */
    if (verbose > 1) printState(stdout, stacks);

    maxoff= 0;
    int win= solve(gather,0);

    if (verbose > 0) printf("maxoff=%d\n",maxoff);
    nplayed++;
    cardsleft+= maxoff;
    if (win == 1)
	nwon++;
    else if (win == 2)
	nabandoned++;

    cleanFound();
    cleanTableau();
    if (unlimited)
	cleanBouquet();
    else
    {
	cleanWaste();
	cleanStock();
    }
    cleanStacks();
    cleanVisited();
}

/* Gather up the cards into the global 'gathered' stack. This has to be
 * non-destructive, since we may not be done solving when it is called.
 */
void gatherAll()
{
    if (gathered == NULL)
	gathered= allocStack(ncard);
    else
	gathered->n= 0;

    gatherFound(gathered);
    gatherTableau(gathered);
    if (unlimited)
	gatherBouquet(gathered);
    else
    {
	gatherStock(gathered);
	gatherWaste(gathered, 0);
    }
    if (gathered->n != ncard)
    {
	printf("Gather Failed - found %d cards\n",gathered->n);
	exit(1);
    }
}

/* How good is a move?
 *
 * Returns 0 if the move is completely safe or manditory. Such moves will not
 * be marked as choice points for backtracking.
 *
 * For other moves, positive values are returned with lower values for better
 * moves.
 *
 * Negative values mean the move should not be done at all.
 *
 * So for Ali Baba:
 *
 *   0 = Any move to the foundation.
 *       Deal a card if waste is empty or contains kings only.
 *       Any move to non-empty tableau space.
 *   1 = Move card into space
 *   2 = Deal a card, otherwise
 */
int rateMove(Stack *src, int index1, int len, Stack *dst)
{
    if (src->type == STOCK)
    {
	/* A deal. Safe if waste is empty or only contains a king.
	 * Not so great otherwise.
	 */
	Stack *ws= stacks + waste[0].id;
	if (ws->n == 0 || (ws->n == 1 && ws->c[0]->n == 13))
	    return 0;
	else
	    return 2;
    }

    /* Moves to foundation are sae */
    if (dst->type == FOUND)
	return 0;

    /* Must be moving in to a tableau space */

    /* If moving into a non-empty space, is safe */
    if (dst->n > 0)
	return 0;

    return 1;
}

void printState(FILE *f, Stack *stks)
{
    printFound(f, stks);
    printTableau(f, stks);
    if (unlimited)
	printBouquet(f, stks);
    else
    {
	printStock(f, stks);
	printWaste(f, stks);
    }
}

int victory()
{
    int off= nOff();
    if (off > maxoff) maxoff= off;
    return (off == ncard);
}

/* Return a quality rating for the current solution. Bigger is better. Usually
 * it's just cards off. This is used to decide which solution to report in
 * cases where we never win.
 */
int quality()
{
    return nOff();
}

void summary()
{
    printf("Played:    %d games\n",nplayed);
    printf("Won:       %d games (%.2f%)\n",nwon,(float)nwon*100/nplayed);
    printf("Abandoned: %d games (%.2f%)\n",nabandoned,(float)nabandoned*100/nplayed);
    printf("Cards Off: %.2f\n",(float)cardsleft/nplayed);
}

/* Comparision function for stack order normalization in currstate() */
static int cmpstacks(const void *p1, const void *p2)
{
    const Stack *s1= (const Stack *)p1;
    const Stack *s2= (const Stack *)p2;
    if (s1->n == 0 || s2->n == 0)
	return s2->n - s1->n;
    int c1= s1->c[0] - deck;
    int c2= s2->c[0] - deck;
    return c2 - c1;
}

/* Return a string that uniquely describes the current state. */
char *currstate()
{
    /* ncards for all the cards on things, 4 for foundations,
     * 10 for list terminators.
     */
    char buf[ncard+30], *p= buf;

    /* Numbers of cards in each foundation pile */
    /* We add one to each count because we don't want any zeros */
    for (int k= 0; k < nfound; k++)
	*(p++)= stacks[foundation[k].id].n + 1;

    /* List of cards on each tableau pile - probably we should normalize
     * the order of tableau piles, sorting them by the first card on them.
     * Not sure it's worth the effort for Ali Baba.
     */
#ifdef SORT
    Stack *norm[10];
    for (int k= 0; k < ntableau; k++)
	norm[k]= stacks + tableau[k].id;
    /* This seg faults for some reason - fix is in indefatigable.c */
    qsort(norm, ntableau, sizeof(Stack *), cmpstacks);

    for (int k= 0; k < ntableau; k++)
    {
	Stack *s= norm[k];
	for (int i= 0; i < s->n; i++)
	    *(p++)= (s->c[i] - deck) + 1;
	*(p++)= ncard + 1; /* The card list terminator */
    }
#else
    for (int k= 0; k < ntableau; k++)
    {
	Stack *s= stacks + tableau[k].id;
	for (int i= 0; i < s->n; i++)
	    *(p++)= (s->c[i] - deck) + 1;
	*(p++)= ncard + 1; /* The card list terminator */
    }
#endif

    /* Number of cards in stock */

    if (!unlimited)
	*(p++)= stacks[stock[0].id].n;

    *p= '\0';

    return strdup(buf);
}
